//
//  LKElearningTestViewController.m
//  YLHelper
//
//  Created by she1323 on 2018/5/8.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "LKElearningTestViewController.h"
#import "LKTestCell.h"
#import "LKVideoTestModel.h"
#import "LKTestpageNameViewController.h"
#import "LKVideoKaoshiModel.h"
#import "LKBottomAccountRightAndWrongView.h"
@interface LKElearningTestViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>{
    NSInteger _secondnumber;
    NSInteger _minutenumber;
}

@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)UICollectionViewFlowLayout *flowLayout;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,strong)LKBaseLabel *timelabel;
@property(nonatomic,strong)NSMutableArray *datalistArray;
@property(nonatomic,assign)NSInteger currentIndex;

@property(nonatomic,strong)NSMutableArray *selectsArray;
@property(nonatomic,strong)UIButton *btn;
@property(nonatomic,assign)NSInteger accountRightNumbers;
@property(nonatomic,assign)NSInteger accountWrongNumbers;
@property(nonatomic,strong)LKBottomAccountRightAndWrongView *accountView;
@property(nonatomic,strong)NSMutableArray *recordCollectArray;
@end

@implementation LKElearningTestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.currentIndex = 0;
    self.accountRightNumbers = 0;
    self.accountWrongNumbers = 0;
    [[NSUserDefaults standardUserDefaults] setObject:@" 0" forKey:@"testWrongAccount"];
    [[NSUserDefaults standardUserDefaults] setObject:@" 0" forKey:@"testRightAccount"];
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(mytimer) userInfo:nil repeats:YES];
//    [_timer setFireDate:[NSDate distantPast]];
    [self setcollectionView];
    [self getExaminationPaperData];
    // Do any additional setup after loading the view.
}
-(void)mytimer{
    _secondnumber ++;
    if (_secondnumber > 59) {
        _secondnumber = 0;
        _minutenumber ++;
    }
    _timelabel.text = [NSString stringWithFormat:@"%02ld:%02ld",_minutenumber,_secondnumber];
}
-(void)setNavgationBackBtn{
    [super setNavgationBackBtn];
    self.btn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btn.size = CGSizeMake(80, 44);
    _btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    _btn.titleLabel.font = [UIFont systemFontOfSize:16];
    [_btn setTitle:@"确定" forState:UIControlStateNormal];
    [_btn setTitle:@"下一题" forState:UIControlStateSelected];
    [_btn setTitleColor:blueDefault forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.btn];
    [_btn addTarget:self action:@selector(sureAnswerOrNext:) forControlEvents:UIControlEventTouchUpInside];
    _secondnumber = 0;
    _minutenumber = 0;
    _timelabel = [LKBaseLabel labelWithFrame:CGRectMake(0, 0, 150, 40) text:[NSString stringWithFormat:@"%02ld:%02ld",_minutenumber,_secondnumber] textColor:ColorRGB(0, 0, 0) font:[UIFont systemFontOfSize:16] textAlignment:NSTextAlignmentCenter backgroundColor:[UIColor clearColor]];
    self.navigationItem.titleView = _timelabel;
    [self.backButton addTarget:self action:@selector(chooseExitTest:) forControlEvents:UIControlEventTouchDownRepeat];
    
}
-(void)chooseExitTest:(UIButton *)btn{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您是否要退出练习？退出将不会保留您的练习结果" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
    
}
-(void)back{
    self.currentIndex = self.collectionView.contentOffset.x / WIDTH;
    if (self.currentIndex == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您是否要退出练习？退出将不会保留您的练习结果" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popViewControllerAnimated:YES];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    _btn.selected = YES;
    [_btn setTitle:@"确定" forState:UIControlStateNormal];
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex - 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    self.accountView.numberLabel.text = [NSString stringWithFormat:@"%ld/%ld",self.currentIndex,self.datalistArray.count];
    NSMutableDictionary *collecDic = self.recordCollectArray[self.currentIndex - 1];
    NSLog(@"收藏的小字典%@",collecDic);
    self.accountView.collectBtn.selected = [[[collecDic allValues] lastObject] boolValue];
//    LKTestCell *cell = (LKTestCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex - 1  inSection:0]];
//    cell.model.hadSureAns = YES;
//    cell.sureAnswer = YES;
//    cell.hithithit = NO;
    
//    [cell.tableView reloadData];
//    NSLog(@"%@",cell.selectValue);
}
/**
 确定答案

 */
-(void)sureAnswerOrNext:(UIButton *)btn{
    if ([btn.titleLabel.text isEqual:@"提交"]) {
        [self commitTestAnser];
        return;
    }
    self.currentIndex = self.collectionView.contentOffset.x / WIDTH;
    if (self.selectsArray.count < self.currentIndex) {
        btn.selected = YES;
    }
    LKTestCell *cell = (LKTestCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex  inSection:0]];
    NSLog(@"cell的section的个数是%ld",cell.tableView.numberOfSections);
    if (!btn.selected) {
        NSMutableArray *anserArr = [[NSMutableArray alloc] init];
        for (NSInteger i = 0; i < cell.selectValue.length; i++) {
            char chara = [cell.selectValue characterAtIndex:i];
            NSString *chartStr = [NSString stringWithFormat:@"%c",chara];
            [anserArr addObject:chartStr];
        }
        NSDictionary *selectDic = [NSDictionary dictionaryWithObjectsAndKeys:anserArr,@"QuestionAnswerName",cell.model.questionBankId,@"QuestionId", nil];
        [self.selectsArray addObject:selectDic];
        
        if ([[[cell.numberLabel.text componentsSeparatedByString:@"/"] firstObject] isEqual:[[cell.numberLabel.text componentsSeparatedByString:@"/"] lastObject]]) {
            if (cell.model.hadSureAns) {
                cell.hithithit = NO;
                [cell.tableView reloadData];
                [cell.tableView layoutIfNeeded];
                [self accountDetailWrongnumerAndRightnumberInformation];
                [_btn setTitle:@"提交" forState:UIControlStateNormal];
                return;
            }
            cell.model.hadSureAns = YES;
            cell.sureAnswer = YES;
            cell.hithithit = YES;
            [cell.tableView reloadData];
            [cell.tableView layoutIfNeeded];
            [self accountDetailWrongnumerAndRightnumberInformation];
            [_btn setTitle:@"提交" forState:UIControlStateNormal];
            return;
        }
        if (cell.model.hadSureAns) {
            btn.selected = !btn.selected;
            cell.hithithit = NO;
            [self accountDetailWrongnumerAndRightnumberInformation];
            return;
        }
        cell.model.hadSureAns = YES;
        cell.sureAnswer = YES;
        cell.hithithit = YES;
        
        [cell.tableView reloadData];
        [cell.tableView layoutIfNeeded];
        [self accountDetailWrongnumerAndRightnumberInformation];
    }else{
        if (self.currentIndex + 1 >= self.datalistArray.count) {
            return;
        }
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex + 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
        self.accountView.numberLabel.text = [NSString stringWithFormat:@"%ld/%ld",self.currentIndex + 2,self.datalistArray.count];
        NSMutableDictionary *collecDic = self.recordCollectArray[self.currentIndex + 1];
        self.accountView.collectBtn.selected = [[[collecDic allValues] lastObject] boolValue];
        NSLog(@"收藏的小字典%@",collecDic);
        [self accountDetailWrongnumerAndRightnumberInformation];
    }

    btn.selected = !btn.selected;
}

/**
 提交测试答案
 */
-(void)commitTestAnser{
    NSMutableDictionary *mutabDic = [[NSMutableDictionary alloc] init];
    NSDictionary *param;
    NSString *url;
    if (self.isKaoshi) {
        url = submitKaoshiUrl;
        param = [NSDictionary dictionaryWithObjectsAndKeys:self.paperId,@"ExaminationPaperId",self.timelabel.text,@"ExpendMinute", nil];
    }else{
        url = submitPracticeUrl;
        param = [NSDictionary dictionaryWithObjectsAndKeys:self.paperId,@"ExaminationPaperId",self.timelabel.text,@"ExpendMinute", nil];
    }
    NSSet *set = [NSSet setWithArray:self.selectsArray];
    NSArray *selectsArra = [set allObjects];
    NSDictionary *param1 = [NSDictionary dictionaryWithObjectsAndKeys:selectsArra,@"AnswerInput", nil];
    [mutabDic addEntriesFromDictionary:param];
    [mutabDic addEntriesFromDictionary:param1];
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:url header:[LKUserInforTool header] parameters:mutabDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        NSString *recoreStr = responseObject[@"result"][@"score"];
        NSString *setRecordStr = [NSString stringWithFormat:@"得分:%@",recoreStr];
        [SVProgressHUD showInfoWithStatus:setRecordStr];
        
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
/**
 设置collectionview
 */
-(void)setcollectionView{
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT - NAVIGATION_BAR_HEIGHT);
    self.flowLayout.minimumLineSpacing = 0;
    self.flowLayout.minimumInteritemSpacing = 0;
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT ,WIDTH, HEIGHT - NAVIGATION_BAR_HEIGHT) collectionViewLayout:self.flowLayout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.panGestureRecognizer.enabled = NO;
    for (NSInteger i = 0; i < self.collectionView.gestureRecognizers.count; i++) {
        UIGestureRecognizer *ges = self.collectionView.gestureRecognizers[i];
        [self.collectionView removeGestureRecognizer:ges];
    }
    [self.view addSubview:self.collectionView];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.scrollEnabled = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    [self.collectionView registerNib:[UINib nibWithNibName:@"LKTestCell" bundle:nil] forCellWithReuseIdentifier:@"LKTestCell"];
    [self.collectionView reloadData];
    [self addBottomView];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.datalistArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    LKTestCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LKTestCell" forIndexPath:indexPath];
    cell.isKaoshi = self.isKaoshi;
    if (self.isKaoshi) {
        cell.kaoshiModel = self.datalistArray[indexPath.row];
    }else{
        cell.model = self.datalistArray[indexPath.row];
    }
    cell.numberLabel.text = [NSString stringWithFormat:@"%ld/%ld",indexPath.row + 1,self.datalistArray.count];
    return cell;
    
}

/**
 获取练习的习题
 */
-(void)getExaminationPaperData{
    NSString *url;
    if (self.isKaoshi) {
        url = startKaoshiUrl;
    }else{
        url = examTestUrl;
    }
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:url header:[LKUserInforTool header] parameters:@{@"Id":self.paperId} progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject[@"result"];
        if (self.isKaoshi) {
            LKVideoKaoshiModel *model = [LKVideoKaoshiModel modelWithDictionary:dic];
            [self.datalistArray addObjectsFromArray:model.questionBank];
            [self.collectionView reloadData];
        }else{
            LKVideoTestModel *model = [LKVideoTestModel modelWithDictionary:dic];
            [self.datalistArray addObjectsFromArray:model.examinationPaperQuestion];
            for (LKExaminationPaperQuestionModel *model in self.datalistArray) {
                NSMutableDictionary *collectDic = [[NSMutableDictionary alloc] initWithDictionary:@{model.questionBankId:@(model.questionBank.isCollection)}];
                [self.recordCollectArray addObject:collectDic];
            }
            [self.collectionView reloadData];
            self.accountView.numberLabel.text = [NSString stringWithFormat:@"1/%ld",self.datalistArray.count];
        }

    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
-(void)dealloc{
    [_timer invalidate];
    _timer = nil;
}
-(NSMutableArray *)datalistArray{
    if (!_datalistArray) {
        _datalistArray = [[NSMutableArray alloc] init];
    }
    return _datalistArray;
}
-(NSMutableArray *)selectsArray{
    if (!_selectsArray) {
        _selectsArray = [[NSMutableArray alloc] init];
    }
    return _selectsArray;
}
-(void)addBottomView{
    self.accountView = [[[NSBundle mainBundle] loadNibNamed:@"LKBottomAccountRightAndWrongView" owner:self options:nil] firstObject];
    [self.view addSubview:self.accountView];
    self.accountView.numberLabel.text = [NSString stringWithFormat:@"1/%ld",self.datalistArray.count];
    [self.accountView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(self.view);
        make.left.equalTo(self.view.mas_left).offset(0);
        make.height.mas_equalTo(48);
    }];
    [self.accountView.collectBtn addTarget:self action:@selector(collectOrNotCollect:) forControlEvents:UIControlEventTouchUpInside];
    [self.view bringSubviewToFront:self.accountView];
    [self accountDetailWrongnumerAndRightnumberInformation];
}
-(void)accountDetailWrongnumerAndRightnumberInformation{
    self.accountWrongNumbers = [[[[[NSUserDefaults standardUserDefaults] objectForKey:@"testWrongAccount"] componentsSeparatedByString:@" "] lastObject] integerValue];
    self.accountRightNumbers = [[[[[NSUserDefaults standardUserDefaults] objectForKey:@"testRightAccount"] componentsSeparatedByString:@" "] lastObject] integerValue];
    NSLog(@"正确个数%ld",self.accountRightNumbers);
    NSLog(@"错误个数%ld",self.accountWrongNumbers);
    NSString *rightsNumber = [NSString stringWithFormat:@" %ld",self.accountRightNumbers];
    NSString *wrongNumber = [NSString stringWithFormat:@" %ld",self.accountWrongNumbers];
    [self.accountView.wrongBtn setTitle:wrongNumber forState:UIControlStateNormal];
    [self.accountView.rightBtn setTitle:rightsNumber forState:UIControlStateNormal];

}

/**
 取消收藏或者收藏

 @param btn 收藏按钮
 */
-(void)collectOrNotCollect:(UIButton *)btn{
    LKExaminationPaperQuestionModel *model = self.datalistArray[self.currentIndex];
    if (!btn.selected) {
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:examTestCollectUrl header:[LKUserInforTool header] parameters:@{@"Id":model.questionBankId} progress:^(NSProgress * _Nullable progress) {
            
        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
            NSMutableDictionary *mutableDic = self.recordCollectArray[self.currentIndex];
            [mutableDic setObject:@(YES) forKey:[[mutableDic allKeys] lastObject]];
            [SVProgressHUD showInfoWithStatus:@"习题收藏成功"];
        } failure:^(NSString * _Nullable errorMessage) {
            
        }];
    }else{
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:examTestCancelCollectUrl header:[LKUserInforTool header] parameters:@{@"Id":model.questionBankId} progress:^(NSProgress * _Nullable progress) {
            
        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
            NSMutableDictionary *mutableDic = self.recordCollectArray[self.currentIndex];
            [mutableDic setObject:@(NO) forKey:[[mutableDic allKeys] lastObject]];
            [SVProgressHUD showInfoWithStatus:@"习题取消收藏"];
        } failure:^(NSString * _Nullable errorMessage) {
            
        }];
    }
    btn.selected = !btn.selected;
}
-(NSMutableArray *)recordCollectArray{
    if (!_recordCollectArray) {
        _recordCollectArray = [[NSMutableArray alloc] init];
    }
    return _recordCollectArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
